package rabbitMQ.topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import rabbitMQ.constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ProducerDemo {
    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();

        //设置参数
        factory.setHost("124.223.31.81");
        factory.setPort(5672);
        factory.setVirtualHost("bite");
        factory.setUsername("study");
        factory.setPassword("study");

        //创建连接Connection
        Connection connection = factory.newConnection();

        Channel channel = connection.createChannel();

        // 创建交换机
        /* exchangeDeclare(String exchange, BuiltinExchangeType type, boolean durable,
        boolean autoDelete, boolean internal, Map<String, Object> arguments)
            参数:
                1. exchange:交换机名称
                2. type:交换机类型
                    * DIRECT("direct"), 定向,直连,routing
                    * FANOUT("fanout"),扇形(⼴播), 每个队列都能收到消息
                    * TOPIC("topic"),通配符
                    * HEADERS("headers") 参数匹配(⼯作⽤的较少)
                3. durable: 是否持久化
                4. autoDelete: ⾃动删除
                5. internal: 内部使⽤, ⼀般false
                6. arguments: 参数
        */
        channel.exchangeDeclare(Constants.TOPIC_EXCHANGE_NAME, BuiltinExchangeType.TOPIC, true, false, false, null);


         //如果没有⼀个hello_world 这样的⼀个队列, 会⾃动创建, 如果有, 则不创建
        channel.queueDeclare(Constants.TOPIC_QUEUE_NAME1, true, false, false, null);
        channel.queueDeclare(Constants.TOPIC_QUEUE_NAME2, true, false, false, null);

        //4. 绑定队列和交换机
        /*
        queueBind(String queue, String exchange, String routingKey, Map<String, Object> arguments)
        参数:
        1. queue: 队列名称
        2. exchange: 交换机名称
        3. routingKey: 路由key, 路由规则
        如果交换机类型为fanout,routingkey设置为"",表⽰每个消费者都可以收到全部信息
        */
        channel.queueBind(Constants.TOPIC_QUEUE_NAME1, Constants.TOPIC_EXCHANGE_NAME,"*.b.*");
        channel.queueBind(Constants.TOPIC_QUEUE_NAME2, Constants.TOPIC_EXCHANGE_NAME,"a.*");
        channel.queueBind(Constants.TOPIC_QUEUE_NAME2, Constants.TOPIC_EXCHANGE_NAME,"c.#");
        // 通过channel发送消息到队列中
        String msg = "Hello rabbitMQ...a.b";
        channel.basicPublish(Constants.TOPIC_EXCHANGE_NAME, "a.b", null, msg.getBytes());
        msg = "Hello rabbitMQ...a.b.c";
        channel.basicPublish(Constants.TOPIC_EXCHANGE_NAME, "a.b.c", null, msg.getBytes());
        msg = "Hello rabbitMQ...c.b.a";
        channel.basicPublish(Constants.TOPIC_EXCHANGE_NAME, "c.b.a", null, msg.getBytes());

        System.out.println("发送成功");

        //释放资源
        channel.close();
        connection.close();

    }
}
